#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <vector>
#include <string>

pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
bool flag = true;

void *myprintA(void *arg)
{
    while (true)
    {
        pthread_mutex_lock(&mtx);
        while (!flag)
        {
            pthread_cond_wait(&cond, &mtx);
        }
        std::string msg = "我是线程A";
        std::cout << msg << std::endl;
        flag = false;
        pthread_cond_broadcast(&cond);
        pthread_mutex_unlock(&mtx);
        usleep(80000);
    }
    return nullptr;
}

void *myprintB(void *arg)
{
    while (true)
    {
        pthread_mutex_lock(&mtx);
        while (flag)
        {
            pthread_cond_wait(&cond, &mtx);
        }
        std::string msg = "我是线程B";
        std::cout << msg << std::endl;
        flag = true;
        pthread_cond_broadcast(&cond);
        pthread_mutex_unlock(&mtx);
        usleep(80000);
    }
    return nullptr;        
}

int main()
{
    pthread_t tid1;
    char name1 = 'A';
    pthread_t tid2;
    char name2 = 'B';

    ::pthread_create(&tid1, nullptr, myprintA, nullptr);
    ::pthread_create(&tid2, nullptr, myprintB, nullptr);

    ::pthread_join(tid1, nullptr);
    ::pthread_join(tid2, nullptr);

    return 0;
}
